<?php
namespace app\common\service;

use think\Request;
use app\common\service\ServiceBase;

class Category extends ServiceBase
{
    /**
     * 获取栏目列表
     *
     * @params $id string 栏目ID
     * @params $child string 子级栏目数组键名
     * @params $order string|array 排序
     * @params $limit int 数量
     * @params $class string 点亮栏目表示(css样式class名称)
     * @return array
     */
    public function getListLayer($id, $child, $order, $limit, $class = 'active')
    {
        $controller = Request::instance()->controller();

        // 如果当前页面为文章
        if (strtolower($controller) == 'article') {
            $articleId = Request::instance()->param('id');
            $article   = \app\common\model\Article::getInfo($articleId);
            $crruntId  = $article['category_id'];
        }

        // 如果当前页面为图书
        if (strtolower($controller) == 'book') {
            $bookId = Request::instance()->param('id');
            $book   = \app\common\model\Book::getInfo($bookId);
            $crruntId  = $book['category_id'];
        }

        // 当前页面为分类
        if (strtolower($controller) == 'category'){
            $alias = Request::instance()->param('alias');
            $crruntId = \app\common\model\Category::getId($alias);
        }

        // 查询当前栏目下所有栏目
        if ($id == 'self') {
            $map['c.parent_id'] = $crruntId;
        }

        // 查询指定栏目
        if ($id != 'self' && $id != 'null') {
            $map['c.id'] = array('in', $id);
        }

        // 查询限制
        $map['c.status'] = array('<>', 1); //0 显示 1隐藏
        $list = \app\common\model\Category::getList($map, $order, $limit);

        // 查询当前栏目的所有父级ID
        $ids = array();
        if (isset($crruntId)) {
            $praents = getParents($list, $crruntId);
            if (!empty($praents)) {
                foreach ($praents as $v) {
                    array_push($ids, $v['id']);
                }
            }
        }

        // 生成栏目列表URL 及点亮标识
        $new_list = array();
        if (!empty($list)) {
            foreach ($list as $k => $v) {
                $v['category_url'] = $this->categoryUrl($v['alias']);
                // 给父级ID添加ACTIVE
                if(in_array($v['id'], $ids)) {
                    $v['active'] = 1; // 该栏目是否高亮
                    $v['class']  = $class; // 导航高亮
                } else {
                    $v['active'] = 0;
                    $v['class']  = '';
                }
                array_push($new_list, $v);
            }
        }

       return list_to_tree($new_list, 'id', 'parent_id', $child, 0);
    }

}